package com.ts.system.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ts.comm.SysNumber;
import com.ts.comm.SysResult;
import com.ts.jdbc.SysDB;
import com.ts.system.dao.PostDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xhc on 2017/5/2.
 */
@Repository
public class PostDaoImpl implements PostDao {

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    /**
     * 添加岗位信息
     *
     * @param postInfo
     * @return
     */
    public SysResult add(HashMap<String, Object> postInfo) {
        String sql="insert into s_Post(fCode,fName,fDeptCode,fOrgCode,fIsStop,fDesc)";
        sql+=" values(:FCODE,:FNAME,:FDEPTCODE,:FORGCODE,:FISSTOP,:FDESC)";
        SysResult sysResult=new SysResult();
        try {
            SysDB.update(jdbcTemplate,sql,postInfo);
        } catch (Exception e) {
            sysResult.onSetErrorMsg(e);
        }
        return  sysResult;
    }

    /**
     * 修改岗位信息
     *
     * @param postInfo
     * @param sPostcode
     * @return
     */
    public SysResult update(HashMap<String, Object> postInfo, String sPostcode) {
        String sql="update s_Post set fName=:fName,fDeptCode=:fDeptCode,fOrgCode=:fOrgCode,fIsStop=:fIsStop,fDesc=:fDesc";
        sql+=" where fCode=:fCode?";
        postInfo.put("fCode",sPostcode);
        SysResult sysResult=new SysResult();
        try {
            SysDB.update(jdbcTemplate,sql,postInfo);
        } catch (Exception e) {
            sysResult.onSetErrorMsg(e);
        }
        return  sysResult;
    }

    /**
     * 删除岗位
     *
     * @param codeList
     * @return
     */
    @Transactional
    public SysResult delete(List codeList) {
        String sql="delete from s_Post ";
        sql+=" where fCode=:fCode";
        SysResult sysResult=new SysResult();
        for(Object codeObject:codeList){
            HashMap<String,Object> map = new HashMap<String,Object>();
            map.put("fCode",codeObject);
            try {
                SysDB.update(jdbcTemplate,sql,map);
            } catch (Exception e) {
                sysResult.onSetErrorMsg(e);
            }
        }
        return  sysResult;
    }

    /**
     * 获得单条岗位
     *
     * @param fPostCode
     * @return
     */
    public SysResult getPost(String fPostCode) {
        StringBuilder sql=new StringBuilder();
        sql.append("select t.fCode,t.fName,d.fname fdeptname,o.fname fOrgName" );
        sql.append(",decode(t.fisstop,0,'否','是'）fisstop" );
        sql.append(" from S_POST t" );
        sql.append(" left join s_department d on t.fdeptcode=d.fcode" );
        sql.append(" left join s_department o on t.forgcode=o.fcode" );
        sql.append(" where t.fcode=:fPostCode");
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("fPostCode",fPostCode);
        SysResult sysResult=new SysResult();
        try {
            List rows = SysDB.getRows(jdbcTemplate,sql.toString(),map);
            sysResult.setRows(rows);
        } catch (Exception e) {
            sysResult.onSetErrorMsg(e);
        }
        return  sysResult;
    }

    /**
     * 查询所有岗位
     *
     * @param fDeptCode
     * @return
     */
    public SysResult query(String fDeptCode) {
        StringBuilder sql=new StringBuilder();
        sql.append("select rownum as FROWNUM, p.fcode as FCODE, p.fname as FNAME, p.fdesc as FDESC , d.fname as FORGNAME, decode(p.fisstop,0,'否',1,'是') as FISSTOP FROM S_POST p left join s_Department d on p.fdeptcode = d.fcode ");
        sql.append("where  d.fcode = :fDeptCode");
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("fDeptCode",fDeptCode);
        SysResult sysResult=new SysResult();
        try {
            List<Map<String, Object>> rows = SysDB.getRows(jdbcTemplate, sql.toString(),map);
            sysResult.setRows(rows);
        } catch (Exception e) {
            sysResult.onSetErrorMsg(e);
        }
        return  sysResult;
    }

    /**
     * 通过fcode查询岗位信息
     * @param fCode
     * @return
     */
    public SysResult getPostInfoByFcode(String fCode) {
        StringBuilder sql=new StringBuilder();
        sql.append("select p.fcode, ");
        sql.append("p.fname, ");
        sql.append("p.fdesc, ");
        sql.append("p.fdeptcode, ");
        sql.append("p.forgcode, ");
        sql.append("d.fname FDEPTNAME, ");
        sql.append("decode(p.fisstop,'0','否','1','是') ");
        sql.append("from s_post p left join s_department d on p.fdeptcode = d.fcode where p.fcode = :fCode");
        SysResult sysResult=new SysResult();
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("fCode",fCode);
        try {
            List<Map<String, Object>> rows = SysDB.getRows(jdbcTemplate, sql.toString(),map);
            sysResult.setRows(rows);
        } catch (Exception e) {
            sysResult.onSetErrorMsg(e);
        }
        return  sysResult;
    }

    /**
     * 查询权限列表
     * @return
     */
    public SysResult getRightList(){
        String SQL = "";
        SQL = "SELECT * FROM (";
        SQL += "         SELECT * FROM (";
        SQL += "                  SELECT fCode fNum,fCode fID,t.fCode,0 fRoleID,fName,fParent,fIsDetail,fLevel,'1' tag ";
        SQL += "                  FROM s_Model t";
        SQL += "         ) a";
        SQL += "         UNION ALL";
        SQL += "         SELECT * FROM (";
        SQL += "                  SELECT s.fCode || '-' || fModelCode fNum,fModelCode fID,to_char(t.fOPID) fOPID,t.fOPID fRoleID";
        SQL += "                        ,t.fOpName,fModelCode fParent,1 fIsDetail,(s.flevel+1) fLevel,'op' tag";
        SQL += "                  FROM s_Model s";
        SQL += "                  left JOIN s_ModelOp t ON t.fModelCode=s.fCode";
        SQL += "                  WHERE t.fOpID >= 0";
        SQL += "         ) b";
        SQL += " ) v";
        SQL += " ORDER BY fID,fNum,fRoleID";
        System.out.println(SQL);
        SysResult sysResult = new SysResult();
        try {
            List<Map<String, Object>> rows =SysDB.getRows(jdbcTemplate,SQL,new HashMap<String, Object>());
            sysResult.setRows(rows);
        } catch (Exception e) {
            sysResult.onSetErrorMsg(e);
        }
        return sysResult;
    }


    /**
     * 根据岗位代码获取岗位的列表
     * @param postCode
     * @return
     */
    public SysResult getPostRightList(String postCode){
        StringBuilder sql = new StringBuilder();
        sql.append("select * from s_postright where fpostcode = :postCode");
        List<Map<String,Object>> rows = null;
        HashMap<String,Object> sqlMap = new HashMap<String,Object>();
        sqlMap.put("postCode",postCode);
        try {
            rows = SysDB.getRows(jdbcTemplate, sql.toString(),sqlMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<Map> resultList = new ArrayList<Map>();
        if(rows!=null){
            for(Map<String,Object> row:rows){
                List<Integer> pidList = SysNumber.toBinaryList(Integer.parseInt(row.get("FOPID").toString()));
                pidList.add(0);
                for(int pid:pidList){
                    Map map = new HashMap();
                    map.put("FROLEID",pid);
                    map.put("FID",row.get("FMODELCODE"));
                    resultList.add(map);
                }
            }
        }

        SysResult sysResult = new SysResult();
        sysResult.setRows(resultList);
        return sysResult;
    }

    /**
     * 设置岗位的权限
     * @param rightMap
     * @return
     */
    @Transactional
    public SysResult setPostRight(Map rightMap) {
        SysResult sysResult = new SysResult();
        String postCode = (String) rightMap.get("postCode");
        JSONArray rightArray = (JSONArray) rightMap.get("checkNodes");
        List<JSONObject> rightList = new ArrayList<JSONObject>();
        List<String> modelList = new ArrayList<String>();
        for(Object rightObject:rightArray){
            JSONObject right = (JSONObject)rightObject;
            if("op".endsWith(right.getString("TAG"))){
                String model = right.getString("FID");
                if(!modelList.contains(model)){
                    modelList.add(model);
                }
                rightList.add(right);
            }
        }

        StringBuilder deleteSql = new StringBuilder();
        deleteSql.append("delete from s_postright where fpostcode = :postCode");
        HashMap<String,Object> deleteMap = new HashMap<String,Object>();
        deleteMap.put("postCode",postCode);
        try {
            SysDB.update(jdbcTemplate,deleteSql.toString(),deleteMap);
        } catch (Exception e) {
            sysResult.onSetErrorMsg(e);
        }

        for(String modelCode:modelList){
            int opId = 0;
            for(JSONObject right:rightList){
                if(modelCode.endsWith(right.getString("FID"))){
                    opId += right.getInteger("FROLEID");
                }
            }
            StringBuilder addSql = new StringBuilder();
            addSql.append("insert into s_postright(fpostcode,fmodelcode,fopid)");
            addSql.append(" values(:postCode,:modelCode,:opId)");
            HashMap<String,Object> addMap = new HashMap<String,Object>();
            addMap.put("postCode",postCode);
            addMap.put("modelCode",modelCode);
            addMap.put("opId",opId);

            try {
                SysDB.update(jdbcTemplate,addSql.toString(),addMap);
            } catch (Exception e) {
                sysResult.onSetErrorMsg(e);
            }
        }
        return sysResult;
    }
}
